package com.example.teachingMaterial.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.model.pojo.TeachingMaterial;
import com.example.model.pojo.User;
import com.example.model.utils.UserHolder;
import com.example.teachingMaterial.mapper.TeachingMaterialMapper;
import com.example.teachingMaterial.service.TeachingMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * 教学资料Service实现类
 * 实现教学资料相关的业务逻辑
 */
@Service
public class TeachingMaterialServiceImpl implements TeachingMaterialService {

    @Autowired
    private TeachingMaterialMapper teachingMaterialMapper;

    @Value("${teaching.material.upload-dir}")
    private String uploadDir;

    @Override
    public Map<String, Object> uploadMaterial(String title, String description, MultipartFile file,
                                              Integer category) throws IOException {

        User user = UserHolder.get();
        Integer role = user.getRole();
        String teacherId = user.getTeacherId();
        String teacherName = user.getName();

        if (role == 0) {
            throw new SecurityException("学生没有权限上传资料");
        }

        // 验证文件
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 创建上传目录
        String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        File directory = new File(uploadDir + dateDir);
        if (!directory.exists()) {
            directory.mkdirs();
        }

        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID() + fileExtension;
        String filePath = dateDir + File.separator + newFilename;
        String fullPath = uploadDir + filePath;

        // 保存文件
        file.transferTo(new File(fullPath));

        // 保存到数据库
        TeachingMaterial material = new TeachingMaterial();
        material.setTitle(title);
        material.setDescription(description);
        material.setFileName(originalFilename);
        material.setFilePath(filePath);
        material.setUploadedBy(Integer.valueOf(teacherId));
        material.setCategory(category);
        material.setDownloadCount(0);
        material.setUploadTime(LocalDateTime.now());

        teachingMaterialMapper.insert(material);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("id", material.getId());
        result.put("title", material.getTitle());
        result.put("description", material.getDescription());
        result.put("teacherId", teacherId);
        result.put("teacherName", teacherName);
        result.put("fileName", material.getFileName());
        result.put("filePath", "/uploads/materials/" + filePath);
        result.put("category", category);
        result.put("downloadCount", 0);
        result.put("uploadTime", material.getUploadTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        return result;
    }

    @Override
    public Map<String, Object> getMaterialList(Integer category, Integer page, Integer size) {
        // 设置默认分页参数
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null || size < 1) {
            size = 10;
        }

        // 分页查询
        Page<TeachingMaterial> pageQuery = new Page<>(page, size);
        Page<TeachingMaterial> resultPage = teachingMaterialMapper.selectByCategory(pageQuery, category);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("total", resultPage.getTotal());
        result.put("pages", resultPage.getPages());
        result.put("page", page);
        result.put("size", size);
        result.put("records", resultPage.getRecords());

        return result;
    }

    @Override
    public TeachingMaterial getMaterialById(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("资料ID不能为空");
        }
        return teachingMaterialMapper.selectById(id);
    }

    @Override
    public boolean deleteMaterial(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("资料ID不能为空");
        }

        // 查询资料
        TeachingMaterial material = teachingMaterialMapper.selectById(id);
        if (material == null) {
            return false;
        }

        User user = UserHolder.get();
        String teacherId = user.getTeacherId();
        // 验证权限（只有上传者可以删除）
        if (!Objects.equals(Integer.valueOf(teacherId), material.getUploadedBy())) {
            throw new SecurityException("没有权限删除该资料");
        }

        // 删除文件
        String fullPath = uploadDir + material.getFilePath();
        File file = new File(fullPath);
        if (file.exists()) {
            file.delete();
        }

        // 删除数据库记录
        return teachingMaterialMapper.deleteById(id) > 0;
    }

    @Override
    public File downloadMaterial(Integer id) throws IOException {
        if (id == null) {
            throw new IllegalArgumentException("资料ID不能为空");
        }

        // 查询资料
        TeachingMaterial material = teachingMaterialMapper.selectById(id);
        if (material == null) {
            throw new IOException("资料不存在");
        }

        // 获取文件路径
        String fullPath = uploadDir + material.getFilePath();
        File file = new File(fullPath);
        if (!file.exists()) {
            throw new IOException("文件不存在");
        }

        return file;
    }
}